import 'dart:async';

import 'package:flutter/material.dart';

/// 跑马灯效果 原文链接
/// https://juejin.im/post/5c55b36051882562811d2ddd
class MarqueeContinuousWidget extends StatefulWidget {
  final Widget child;
  final Duration duration;
  final double stepOffset;
  const MarqueeContinuousWidget({this.child, this.duration, this.stepOffset});

  @override
  State<StatefulWidget> createState() {
    return _MarqueeContinuousState();
  }
}

class _MarqueeContinuousState extends State<MarqueeContinuousWidget> {
  ScrollController _controller;
  Timer _timer;
  double _offset = 0.0;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController(initialScrollOffset: _offset);
    _timer = Timer.periodic(widget.duration, (timer) {
      double newOffset = _controller.offset + widget.stepOffset;
      if (newOffset != _offset) {
        _offset = newOffset;
        _controller.animateTo(_offset,
            duration: widget.duration, curve: Curves.linear);
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        scrollDirection: Axis.horizontal,
        controller: _controller,
        itemBuilder: (context, index) {
          return widget.child;
        });
  }
}
